package cn.firstsoft.modules.workflow.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.springside.core.commons.BaseManageController;

import cn.firstsoft.modules.workflow.domain.WorkflowIntegration;
import cn.firstsoft.modules.workflow.service.logic.WorkflowIntegrationManager;

public class WorkflowIntegrationManagerController
  extends BaseManageController
{
  private WorkflowIntegrationManager workflowIntegrationManager;
  private static final String BASEDATALISTSHOW_VIEW = "/modules/workflow/workflowIntegration_basedata_list.jsp";
  private static final String BASEDATATREESHOW_VIEW = "/modules/workflow/workflowIntegration_basedata_tree.jsp";
  
  public void setWorkflowIntegrationManager(WorkflowIntegrationManager workflowIntegrationManager)
  {
    this.workflowIntegrationManager = workflowIntegrationManager;
  }
  
  public WorkflowIntegrationManagerController()
  {
    this.listView = "/modules/workflow/workflowIntegration_list.jsp";
    this.editView = "/modules/workflow/workflowIntegration_edit.jsp";
    this.showView = "/modules/workflow/workflowIntegration_show.jsp";
    this.successView = "redirect:/modules/workflow/workflowIntegration.do";
  }
  
  protected void onList(HttpServletRequest request, HttpServletResponse response, ModelAndView mav)
    throws Exception
  {
    mav.addObject("workflowIntegrations", this.workflowIntegrationManager.getAllWorkflowIntegration());
  }
  
  protected void onQuery(HttpServletRequest request, HttpServletResponse response, ModelAndView mav)
    throws Exception
  {
    Map map = WebUtils.getParametersStartingWith(request, "search_");
    mav.addObject("workflowIntegrations", this.workflowIntegrationManager.findWorkflowIntegration(map));
  }
  
  protected void onEdit(HttpServletRequest request, HttpServletResponse response, ModelAndView mav)
    throws Exception
  {
    Integer id = new Integer(request.getParameter("id"));
    mav.addObject("workflowIntegration", this.workflowIntegrationManager.getWorkflowIntegration(id));
  }
  
  protected void onShow(HttpServletRequest request, HttpServletResponse response, ModelAndView mav)
    throws Exception
  {
    Integer id = new Integer(request.getParameter("id"));
    mav.addObject("workflowIntegration", this.workflowIntegrationManager.getWorkflowIntegration(id));
  }
  
  protected void onSave(HttpServletRequest request, HttpServletResponse response, ModelAndView mav, boolean isNew)
    throws Exception
  {
    WorkflowIntegration workflowIntegration = null;
    if (isNew)
    {
      workflowIntegration = new WorkflowIntegration();
    }
    else
    {
      Integer id = new Integer(request.getParameter("id"));
      workflowIntegration = this.workflowIntegrationManager.getWorkflowIntegration(id);
    }
    BindingResult result = bindObject(request, workflowIntegration);
    if (result.hasErrors())
    {
      onBindError(request, result, mav, this.editView + "?method=" + (isNew ? "create" : "edit"));
      return;
    }
    this.workflowIntegrationManager.saveWorkflowIntegration(workflowIntegration);
    
    saveMessage(request, getMessage(request, "common_label1", "数据") + (
      isNew ? getMessage(request, "common_label2", "新增") : getMessage(request, "common_label3", "保存")) + getMessage(request, "common_label4", "成功") + 
      "!");
  }
  
  protected void onRemoveAll(HttpServletRequest request, HttpServletResponse response, ModelAndView mav)
    throws Exception
  {
    String[] ids = request.getParameterValues("itemlist");
    if (ids != null)
    {
      for (int i = 0; i < ids.length; i++) {
        this.workflowIntegrationManager.removeWorkflowIntegration(new Integer(ids[i]));
      }
      saveMessage(request, getMessage(request, "common_label5", "成功删除") + ids.length + getMessage(request, "common_label6", "条纪录"));
    }
  }
  
  public ModelAndView baseDataShow(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mav = null;
    String flowfieldId = request.getParameter("flowfieldId");
    WorkflowIntegration workflowIntegration = this.workflowIntegrationManager.getWorkflowIntegrationByFieldId(flowfieldId);
    
    mav = onBaseDataShow(request, response, workflowIntegration);
    return mav;
  }
  
 
  private void addObject(HttpServletRequest request, ModelAndView mav, WorkflowIntegration workflowIntegration)
    throws Exception
  {
    List<Map> externalBaseData = null;
    String fieldName = request.getParameter("fieldName") == null ? "" : String.valueOf(request.getParameter("fieldName"));
    try
    {
      externalBaseData = this.workflowIntegrationManager.findBaseData(workflowIntegration);
    }
    catch (Exception e)
    {
      String error = e.getCause() == null ? null : e.getCause().getMessage();
      error = error == null ? e.getMessage() : error;
      mav.addObject("exceptionMsg", "异常：" + error);
    }
    if (externalBaseData == null) {
      return;
    }
    List allColumns = this.workflowIntegrationManager.getAllColumns(externalBaseData);
    

    mav.addObject("allColumns", allColumns);
    mav.addObject("allColumnsLength", Integer.valueOf(allColumns.size()));
    if ("3".equals(workflowIntegration.getDisplayMode()))
    {
      String msg = this.workflowIntegrationManager.checkTreeData(externalBaseData);
      if (msg.length() > 1)
      {
        saveMessage(request, msg);
        return;
      }
      mav.addObject("externalBaseDatas", externalBaseData);
    }
    else
    {
      mav.addObject("externalBaseDatas", externalBaseData);
    }
    String integrationListDetail = workflowIntegration.getListDetail();
    Map<String, List> clomnMap = this.workflowIntegrationManager.getColumns(externalBaseData, integrationListDetail);
    List<Map<String, String>> columns = (List)clomnMap.get("rightColmns");
    List<Map<String, String>> wrongColumns = (List)clomnMap.get("wrongColmns");
    mav.addObject("columns", columns);
    mav.addObject("wrongColumns", wrongColumns);
    

    String integrationCondition = workflowIntegration.getCondition();
    List<Map<String, String>> conditionMatchList = new ArrayList();
    this.workflowIntegrationManager.getMatchList(integrationCondition, conditionMatchList);
    mav.addObject("conditions", conditionMatchList);
    



    String formfield = workflowIntegration.getFormField();
    if ((StringUtils.isNotEmpty(formfield)) && (workflowIntegration.getWorkflowFlowfield() != null))
    {
      String formfieldIds = this.workflowIntegrationManager.getFormFieldId(workflowIntegration, formfield);
      formfieldIds = handleFormFields(fieldName, formfieldIds);
      mav.addObject("formfieldIds", formfieldIds);
    }
    else
    {
      mav.addObject("formfieldIds", formfield);
    }
  }
  
  private String handleFormFields(String fieldName, String formfieldIds)
  {
    if (StringUtils.isBlank(fieldName)) {
      return formfieldIds;
    }
    StringBuilder sb = new StringBuilder();
    String[] fielArr = formfieldIds.split(",");
    int pos = 1;
    



    String temp = fieldName.substring(fieldName.length() - 3);
    






    temp = temp.replaceAll("\\D", "");
    if (temp.length() > 0) {
      pos = Integer.valueOf(temp).intValue();
    }
    for (int i = 0; i < fielArr.length; i++)
    {
      String[] arr_ = fielArr[i].split("\\|");
      if (fieldName.contains(arr_[1])) {
        arr_[1] = fieldName;
      } else if (arr_[1].contains("ZZfieldstr")) {
        arr_[1] = (arr_[1] + pos);
      }
      if (sb.length() < 1) {
        sb.append(arr_[0].concat("|" + arr_[1]).concat("|" + arr_[2]));
      } else {
        sb.append("," + arr_[0].concat(new StringBuilder("|").append(arr_[1]).toString()).concat(new StringBuilder("|").append(arr_[2]).toString()));
      }
    }
    return sb.toString();
  }
  
  public void buildCondition(Map map, WorkflowIntegration workflowIntegration)
  {
    String sql = workflowIntegration.getSqlDetail();
    sql = this.workflowIntegrationManager.buildConditionStr(map, sql);
    workflowIntegration.setSqlDetail(sql);
  }
  
  protected void onCreate(HttpServletRequest request, HttpServletResponse response, ModelAndView mav)
    throws Exception
  {}
  
  protected void referenceData(HttpServletRequest request, Map model) {}
  
//============================================================  
//==================二次开发F7支持多选=============================
//============================================================  
  /*
  public ModelAndView onBaseDataShow(HttpServletRequest request, HttpServletResponse response, WorkflowIntegration workflowIntegration)
    throws Exception
  {
    ModelAndView mav = new ModelAndView();
    Map map = WebUtils.getParametersStartingWith(request, "search_");
    if (map.size() > 0) {
      buildCondition(map, workflowIntegration);
    }
    addObject(request, mav, workflowIntegration);
    if ("2".equals(workflowIntegration.getDisplayMode())) {
      mav.setViewName("/modules/workflow/workflowIntegration_basedata_list.jsp");
    } else if ("3".equals(workflowIntegration.getDisplayMode())) {
      mav.setViewName("/modules/workflow/workflowIntegration_basedata_tree.jsp");
    }
    return mav;
  }*/
  
  
  /**
   * 原来DisplayMode:2:列表,3：树型，新增 DisplayMode：ex作为列表多选处理。
   * @param request
   * @param response
   * @param workflowIntegration
   * @return
   * @throws Exception
   */
  
  
  public ModelAndView onBaseDataShow(HttpServletRequest request, HttpServletResponse response, WorkflowIntegration workflowIntegration)
		    throws Exception
  {
		    ModelAndView mav = new ModelAndView();
		    Map map = WebUtils.getParametersStartingWith(request, "search_");

		    if (map.size() > 0) {
		      buildCondition(map, workflowIntegration);
		    }

		    addObject(request, mav, workflowIntegration);

		    if ("2".equals(workflowIntegration.getDisplayMode()))
		      mav.setViewName("/modules/workflow/workflowIntegration_basedata_list.jsp");
		    else if ("3".equals(workflowIntegration.getDisplayMode())) {
		      mav.setViewName("/modules/workflow/workflowIntegration_basedata_tree.jsp");
		    }else if ("ex".equals(workflowIntegration.getDisplayMode())) {
		        mav.setViewName("/modules/workflow/workflowIntegration_basedataex_list.jsp");
		    }
		    return mav;
  }
  
  
}
